<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="订单编号" prop="orderId">
        <el-input
          v-model="queryParams.orderId"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="服务名称" prop="serviceDetailsName">
        <el-input
          v-model="queryParams.serviceDetailsName"
          placeholder="请输入服务名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="星级评分" prop="rate">
        <el-select v-model="queryParams.rate" style="width: 150px" placeholder="请选择星级评分" clearable>
          <el-option label="1星" :value="1" />
          <el-option label="2星" :value="2" />
          <el-option label="3星" :value="3" />
          <el-option label="4星" :value="4" />
          <el-option label="5星" :value="5" />
        </el-select>
      </el-form-item>
      <el-form-item label="预约时间" style="width: 308px">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          @change="handleDateRangeChange"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['orderManagement:evaluateManagement:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['orderManagement:evaluateManagement:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['orderManagement:evaluateManagement:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['orderManagement:evaluateManagement:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="evaluateManagementList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单编号" align="center" prop="orderId" width="150" show-overflow-tooltip />
      <el-table-column label="服务名称" align="center" prop="serviceDetailsName" width="130" show-overflow-tooltip />
      <el-table-column label="评价者" align="center" width="120">
        <template #default="scope">
          <div class="evaluator-info">
            <div class="user-name">{{ scope.row.carUserName || '--' }}</div>
            <div class="user-phone">{{ scope.row.carUserPhone || '--' }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="商家名称" align="center" prop="carMerchantName" width="140" show-overflow-tooltip />
      <el-table-column label="星级评分" align="center" prop="rate" width="130">
          <template #default="scope">
            <el-rate 
              v-model="scope.row.rate"
              disabled 
              :colors="['#F7BA2A', '#F7BA2A', '#F7BA2A']"
            />
          </template>
        </el-table-column>
      <el-table-column label="评价图片" align="center" prop="imgs" width="120">
        <template #default="scope">
          <div v-if="scope.row.imgs" class="image-preview">
            <el-image 
              v-for="(img, index) in parseImages(scope.row.imgs)" 
              :key="index"
              :src="img" 
              :preview-src-list="parseImages(scope.row.imgs)"
              style="width: 30px; height: 30px; margin: 2px"
              fit="cover"
            />
          </div>
          <span v-else class="text-gray-400">无图片</span>
        </template>
      </el-table-column>
      <el-table-column label="评价内容" align="center" prop="content" width="200" show-overflow-tooltip />
      <el-table-column label="评价时间" align="center" prop="time" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.time, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="160">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleView(scope.row)" v-hasPermi="['orderManagement:evaluateManagement:query']">查看</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['orderManagement:evaluateManagement:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['orderManagement:evaluateManagement:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改评价管理对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="evaluateManagementRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户ID" prop="userId">
              <el-input v-model="form.userId" placeholder="请输入用户ID" :disabled="form.id != null" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商家ID" prop="merchantId">
              <el-input v-model="form.merchantId" placeholder="请输入商家ID" :disabled="form.id != null" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="订单编号" prop="orderId">
          <el-input v-model="form.orderId" placeholder="请输入订单编号" :disabled="form.id != null" />
        </el-form-item>
        <el-form-item label="星级评分" prop="rate">
          <el-rate 
            v-model="form.rate" 
            show-text 
            :texts="['极差', '失望', '一般', '满意', '惊喜']"
            :max="5"
          />
        </el-form-item>
        <el-form-item label="评价图片" prop="imgs">
          <image-upload v-model="form.imgs" :limit="5" />
        </el-form-item>
        <el-form-item label="评价内容" prop="content">
          <el-input 
            v-model="form.content" 
            type="textarea" 
            :rows="4" 
            placeholder="请输入评价内容"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="评价时间" prop="time">
          <el-date-picker 
            v-model="form.time"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择评价时间"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看评价详情对话框 -->
    <el-dialog title="评价详情" v-model="viewOpen" width="600px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单编号">{{ viewData.orderId }}</el-descriptions-item>
        <el-descriptions-item label="服务名称">{{ viewData.serviceDetailsName }}</el-descriptions-item>
        <el-descriptions-item label="用户姓名">{{ viewData.carUserName }}</el-descriptions-item>
        <el-descriptions-item label="用户手机">{{ viewData.carUserPhone }}</el-descriptions-item>
        <el-descriptions-item label="商家名称">{{ viewData.carMerchantName }}</el-descriptions-item>
        <el-descriptions-item label="星级评分">
          <el-rate v-model="viewData.rate" disabled show-score text-color="#ff9900" score-template="{value}星" />
        </el-descriptions-item>
        <el-descriptions-item label="评价时间" :span="2">
          {{ parseTime(viewData.time, '{y}-{m}-{d} {h}:{i}:{s}') }}
        </el-descriptions-item>
        <el-descriptions-item label="评价内容" :span="2">
          <div class="content-text">{{ viewData.content || '无评价内容' }}</div>
        </el-descriptions-item>
        <el-descriptions-item label="评价图片" :span="2" v-if="viewData.imgs">
          <div class="image-gallery">
            <el-image 
              v-for="(img, index) in parseImages(viewData.imgs)" 
              :key="index"
              :src="img" 
              :preview-src-list="parseImages(viewData.imgs)"
              style="width: 80px; height: 80px; margin: 4px"
              fit="cover"
            />
          </div>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="EvaluateManagement">
import { listEvaluateManagement, getEvaluateManagement, delEvaluateManagement, addEvaluateManagement, updateEvaluateManagement } from "@/api/vehicle/orderManagement/evaluateManagement.js"

const { proxy } = getCurrentInstance()

const evaluateManagementList = ref([])
const open = ref(false)
const viewOpen = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const dateRange = ref([])
const viewData = ref({})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderId: null,
    serviceDetailsName: null,
    rate: null,
    startTime: null,
    endTime: null
  },
  rules: {
    userId: [
      { required: true, message: "用户ID不能为空", trigger: "blur" }
    ],
    merchantId: [
      { required: true, message: "商家ID不能为空", trigger: "blur" }
    ],
    orderId: [
      { required: true, message: "订单编号不能为空", trigger: "blur" }
    ],
    rate: [
      { required: true, message: "星级评分不能为空", trigger: "change" }
    ],
    content: [
      { required: true, message: "评价内容不能为空", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询评价管理列表 */
function getList() {
  loading.value = true
  listEvaluateManagement(queryParams.value).then(response => {
    evaluateManagementList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    userId: null,
    merchantId: null,
    orderId: null,
    rate: null,
    imgs: null,
    content: null,
    time: null,
    deleted: 0
  }
  proxy.resetForm("evaluateManagementRef")
}

/** 处理日期范围变化 */
function handleDateRangeChange(dates) {
  if (dates && dates.length === 2) {
    queryParams.value.startTime = dates[0]
    queryParams.value.endTime = dates[1]
  } else {
    queryParams.value.startTime = null
    queryParams.value.endTime = null
  }
}

/** 解析图片字符串 */
function parseImages(imgStr) {
  if (!imgStr) return []
  try {
    // 如果是JSON字符串，解析为数组
    if (imgStr.startsWith('[') && imgStr.endsWith(']')) {
      return JSON.parse(imgStr)
    }
    // 如果是逗号分隔的字符串
    return imgStr.split(',').filter(img => img.trim())
  } catch (error) {
    console.error('解析图片失败:', error)
    return imgStr.split(',').filter(img => img.trim())
  }
}

/** 查看按钮操作 */
function handleView(row) {
  viewData.value = { ...row }
  viewOpen.value = true
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = []
  queryParams.value.startTime = null
  queryParams.value.endTime = null
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加评价管理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getEvaluateManagement(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改评价管理"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["evaluateManagementRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateEvaluateManagement(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addEvaluateManagement(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除评价管理编号为"' + _ids + '"的数据项？').then(function() {
    return delEvaluateManagement(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('orderManagement/evaluateManagement/export', {
    ...queryParams.value
  }, `evaluateManagement_${new Date().getTime()}.xlsx`)
}

getList()
</script>

<style scoped>
.image-preview {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.image-gallery {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.content-text {
  line-height: 1.6;
  word-break: break-word;
  max-height: 120px;
  overflow-y: auto;
}

.text-gray-400 {
  color: #9ca3af;
}

/* 评价者信息样式 */
.evaluator-info {
  text-align: center;
  line-height: 1.4;
}

.user-name {
  color: #333;
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 2px;
}

.user-phone {
  color: #666;
  font-size: 12px;
}

:deep(.el-rate__text) {
  font-size: 12px;
  margin-left: 8px;
}

:deep(.el-descriptions__body .el-descriptions__table) {
  table-layout: fixed;
}

:deep(.el-descriptions__content) {
  word-break: break-word;
}
</style>
